<template>
  <div class="math-practice">
    <div class="content-container">
      <!-- 顶部控制面板 -->
      <div class="control-panel">
      <!-- 左上方控制区 -->
      <div class="left-controls">
        <n-space align="center">
          <span>生成</span>
          <n-input-number
            v-model:value="questionCount"
            :min="1"
            :max="100"
            placeholder="题目数量"
            style="width: 120px"
          />
          <span>题</span>
          <n-select
            v-model:value="questionType"
            :options="[
              { label: '加法', value: 'addition' },
              { label: '减法', value: 'subtraction' },
              { label: '混合', value: 'mixed' }
            ]"
            style="width: 100px"
          />
          <n-input-number
            v-model:value="timeLimit"
            :min="0"
            placeholder="限制时间"
            style="width: 120px"
          />
          <span>分钟</span>
          <n-button size="small" @click="showAdvancedSettings = true">更多设置</n-button>
          <n-checkbox v-model:checked="isHandwritingMode">手写模式</n-checkbox>
          <n-button type="primary" @click="generateQuestions">刷新</n-button>
          <n-button type="success" @click="startTimer" :disabled="!questions.length">开始</n-button>
        </n-space>
      </div>
      
      <!-- 右上方计时器 -->
      <div class="right-controls">
        <n-statistic label="时间" :value="displayTime" />
      </div>
    </div>

    <!-- 分数显示 -->
    <div class="score-panel" v-if="questions.length && isSubmitted">
      <n-statistic label="得分" :value="score" suffix="分" class="score-display" />
      <n-statistic label="满分" :value="questions.length" suffix="分" />
      <div v-if="showCongratulations" class="congratulations">
        <n-alert title="恭喜！" type="success">
          🎉 太棒了！你获得了满分！继续保持！
        </n-alert>
      </div>
    </div>

    <!-- 题目显示区域 -->
    <div class="questions-container" v-if="questions.length">
      <div class="questions-grid">
        <div 
          v-for="(question, index) in questions" 
          :key="index"
          class="question-item"
        >
          <div class="question-text">
            {{ question.num1 }} {{ question.operator }} {{ question.num2 }} = 
          </div>
          <n-input
            v-model:value="question.userAnswer"
            type="text"
            placeholder="?"
            style="width: 80px; margin-left: 8px"
            :disabled="!isStarted || isSubmitted"
            :readonly="isHandwritingMode"
            @click="isHandwritingMode && isStarted && !isSubmitted ? openHandwritingInput(index) : null"
          />
          <n-button 
            size="small" 
            type="info" 
            @click="showAnswer(question)"
            style="margin-left: 8px"
          >
            答案
          </n-button>
          <div class="result-indicator" v-if="isSubmitted && question.isAnswered">
            <n-icon size="20" :color="question.isCorrect ? '#18a058' : '#d03050'">
                <CheckmarkCircle v-if="question.isCorrect" />
                <CloseCircle v-else />
              </n-icon>
          </div>
        </div>
      </div>
      
      <!-- 提交按钮 -->
      <div class="submit-container" v-if="!isSubmitted">
        <n-button 
          type="primary" 
          size="large" 
          @click="submitAnswers"
          :disabled="!hasAnyAnswer"
          class="submit-button"
        >
          提交答案
        </n-button>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <n-empty description="点击刷新按钮生成算数题">
        <template #extra>
          <n-button size="small" @click="generateQuestions">生成题目</n-button>
        </template>
      </n-empty>
    </div>
    </div>
  </div>

  <!-- 手写弹窗 -->
  <n-modal 
    v-model:show="showHandwritingModal" 
    preset="card" 
    title="手写输入" 
    style="width: 500px"
    :mask-closable="false"
  >
    <div class="handwriting-container">
      <div class="question-display" v-if="currentQuestionIndex >= 0">
        <h3>{{ questions[currentQuestionIndex]?.num1 }} {{ questions[currentQuestionIndex]?.operator }} {{ questions[currentQuestionIndex]?.num2 }} = ?</h3>
      </div>
      <canvas 
        ref="handwritingCanvas"
        width="450" 
        height="300" 
        style="border: 2px solid #ccc; border-radius: 8px; background: white; cursor: crosshair;"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
        @touchstart="startDrawing"
        @touchmove="draw"
        @touchend="stopDrawing"
      ></canvas>
      <div class="handwriting-controls" style="margin-top: 16px; display: flex; justify-content: space-between;">
        <n-button @click="clearCanvas">清除</n-button>
        <n-space>
          <n-button @click="closeHandwritingModal">取消</n-button>
          <n-button type="primary" @click="recognizeHandwriting">识别并确定</n-button>
        </n-space>
      </div>
    </div>
  </n-modal>

  <!-- 高级设置弹窗 -->
  <n-modal 
    v-model:show="showAdvancedSettings" 
    preset="card" 
    title="高级设置" 
    style="width: 400px"
  >
    <div class="advanced-settings">
      <n-space vertical size="large">
        <div class="setting-item">
          <n-checkbox v-model:checked="allowAdditionOver100">
            加法答案可以超过100
          </n-checkbox>
          <p class="setting-description">
            勾选后，加法题目的答案可能会超过100。默认情况下答案不超过100。
          </p>
        </div>
        
        <div class="setting-item">
          <n-checkbox v-model:checked="allowNegativeSubtraction">
            减法可以出现负数
          </n-checkbox>
          <p class="setting-description">
            勾选后，减法题目可能会出现负数答案。默认情况下不会出现负数。
          </p>
        </div>
      </n-space>
      
      <div style="margin-top: 24px; text-align: right;">
        <n-space>
          <n-button @click="showAdvancedSettings = false">取消</n-button>
          <n-button type="primary" @click="applyAdvancedSettings">应用设置</n-button>
        </n-space>
      </div>
    </div>
  </n-modal>

  <!-- 解题思路弹窗 -->
  <n-modal 
    v-model:show="showSolutionModal" 
    preset="card" 
    title="解题思路" 
    style="width: 600px"
    :mask-closable="false"
  >
    <div class="solution-container">
      <div class="solution-question" v-if="currentSolutionQuestion">
        <h3>{{ currentSolutionQuestion.num1 }} {{ currentSolutionQuestion.operator }} {{ currentSolutionQuestion.num2 }} = {{ currentSolutionQuestion.answer }}</h3>
        <p class="solution-method-title">
          {{ currentSolutionQuestion.operator === '+' ? '凑十法解题步骤：' : '借十法解题步骤：' }}
        </p>
      </div>
      
      <canvas 
        ref="solutionCanvas"
        width="550" 
        height="400" 
        style="border: 2px solid #e0e0e0; border-radius: 8px; background: white; margin: 16px 0;"
      ></canvas>
      
      <div class="solution-controls" style="text-align: right; margin-top: 16px;">
        <n-space>
          <n-button @click="redrawSolution">重新演示</n-button>
          <n-button type="primary" @click="closeSolutionModal">关闭</n-button>
        </n-space>
      </div>
    </div>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, computed, onUnmounted, nextTick, h } from 'vue'
import { CheckmarkCircle, CloseCircle } from '@vicons/ionicons5'
import { useDialog } from 'naive-ui'

interface Question {
  num1: number
  num2: number
  operator: '+' | '-'
  answer: number
  userAnswer: string
  isAnswered: boolean
  isCorrect: boolean
}

// 弹窗实例
const dialog = useDialog()

// 响应式数据
const questionCount = ref(10)
const timeLimit = ref<number | null>(null)
const questionType = ref('mixed') // 'addition', 'subtraction', 'mixed'
const questions = ref<Question[]>([])
const timer = ref<number | null>(null)
const elapsedTime = ref(0)
const isTimerRunning = ref(false)
const isFinished = ref(false)
const isSubmitted = ref(false)
const isStarted = ref(false)
const isHandwritingMode = ref(false)
const showHandwritingModal = ref(false)
const currentQuestionIndex = ref(-1)

// 高级设置
const showAdvancedSettings = ref(false)
const allowAdditionOver100 = ref(false) // 加法答案是否可以超过100
const allowNegativeSubtraction = ref(false) // 减法是否可以出现负数

// 解题思路
const showSolutionModal = ref(false)
const currentSolutionQuestion = ref<Question | null>(null)
const solutionCanvas = ref<HTMLCanvasElement>()

// 计算属性
const score = computed(() => {
  return questions.value.filter(q => q.isCorrect).length
})

const displayTime = computed(() => {
  if (timeLimit.value && timeLimit.value > 0) {
    // 倒计时模式
    const remaining = Math.max(0, timeLimit.value * 60 - elapsedTime.value)
    const minutes = Math.floor(remaining / 60)
    const seconds = remaining % 60
    return `${minutes}:${seconds.toString().padStart(2, '0')}`
  } else {
    // 正向计时模式
    const minutes = Math.floor(elapsedTime.value / 60)
    const seconds = elapsedTime.value % 60
    return `${minutes}:${seconds.toString().padStart(2, '0')}`
  }
})

const showCongratulations = computed(() => {
  return isSubmitted.value && questions.value.length > 0 && score.value === questions.value.length && 
         questions.value.every(q => q.isAnswered)
})

const hasAnyAnswer = computed(() => {
  return isStarted.value && questions.value.some(q => q.userAnswer.trim() !== '')
})

// 生成算数题
const generateQuestions = () => {
  questions.value = []
  isFinished.value = false
  isSubmitted.value = false
  isStarted.value = false
  elapsedTime.value = 0
  stopTimer()
  
  for (let i = 0; i < questionCount.value; i++) {
    let finalNum1: number, finalNum2: number, answer: number, operator: string
    
    // 根据选择的题目类型决定运算符
    if (questionType.value === 'addition') {
      operator = '+'
    } else if (questionType.value === 'subtraction') {
      operator = '-'
    } else {
      // 混合模式：50%加法，50%减法
      operator = Math.random() > 0.5 ? '+' : '-'
    }
    
    if (operator === '+') {
      // 加法题目生成
      if (allowAdditionOver100.value) {
        // 允许答案超过100
        finalNum1 = Math.floor(Math.random() * 200) + 1
        finalNum2 = Math.floor(Math.random() * 200) + 1
      } else {
        // 限制答案不超过100
        finalNum1 = Math.floor(Math.random() * 50) + 1
        finalNum2 = Math.floor(Math.random() * (100 - finalNum1)) + 1
      }
      answer = finalNum1 + finalNum2
    } else {
      // 减法题目生成
      if (allowNegativeSubtraction.value) {
        // 允许负数答案
        finalNum1 = Math.floor(Math.random() * 100) + 1
        finalNum2 = Math.floor(Math.random() * 150) + 1
      } else {
        // 确保减法结果为正数或零
        const num1 = Math.floor(Math.random() * 100) + 1
        const num2 = Math.floor(Math.random() * 100) + 1
        finalNum1 = Math.max(num1, num2)
        finalNum2 = Math.min(num1, num2)
      }
      answer = finalNum1 - finalNum2
    }
    
    questions.value.push({
      num1: finalNum1,
      num2: finalNum2,
      operator,
      answer,
      userAnswer: '',
      isAnswered: false,
      isCorrect: false
    })
  }
}

// 开始计时
const startTimer = () => {
  if (isTimerRunning.value) return
  
  isStarted.value = true
  isTimerRunning.value = true
  timer.value = setInterval(() => {
    elapsedTime.value++
    
    // 检查倒计时是否结束
    if (timeLimit.value && timeLimit.value > 0 && elapsedTime.value >= timeLimit.value * 60) {
      finishExercise()
    }
  }, 1000)
}

// 停止计时
const stopTimer = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
  isTimerRunning.value = false
}

// 结束练习
const finishExercise = () => {
  stopTimer()
  isFinished.value = true
}

// 提交答案
const submitAnswers = () => {
  // 检查所有答案
  questions.value.forEach(question => {
    const userAnswer = parseInt(question.userAnswer)
    
    if (!isNaN(userAnswer)) {
      question.isAnswered = true
      question.isCorrect = userAnswer === question.answer
    } else {
      question.isAnswered = false
      question.isCorrect = false
    }
  })
  
  isSubmitted.value = true
  finishExercise()
}

// 显示答案
const showAnswer = (question: Question) => {
  dialog.info({
    title: '题目答案',
    content: `${question.num1} ${question.operator} ${question.num2} = ${question.answer}`,
    positiveText: '确定'
  })
}

// 手写相关
const handwritingCanvas = ref<HTMLCanvasElement>()
let isDrawing = false
let lastX = 0
let lastY = 0

// 打开手写输入框
const openHandwritingInput = (questionIndex: number) => {
  if (!isHandwritingMode.value) return
  
  currentQuestionIndex.value = questionIndex
  showHandwritingModal.value = true
  
  // 等待DOM更新后初始化canvas
  nextTick(() => {
    if (handwritingCanvas.value) {
      const ctx = handwritingCanvas.value.getContext('2d')
      if (ctx) {
        ctx.strokeStyle = '#000'
        ctx.lineWidth = 3
        ctx.lineCap = 'round'
        ctx.lineJoin = 'round'
      }
    }
  })
}

// 开始绘制
const startDrawing = (e: MouseEvent | TouchEvent) => {
  isDrawing = true
  const rect = handwritingCanvas.value?.getBoundingClientRect()
  if (!rect) return
  
  if (e instanceof MouseEvent) {
    lastX = e.clientX - rect.left
    lastY = e.clientY - rect.top
  } else {
    e.preventDefault()
    const touch = e.touches[0]
    lastX = touch.clientX - rect.left
    lastY = touch.clientY - rect.top
  }
}

// 绘制
const draw = (e: MouseEvent | TouchEvent) => {
  if (!isDrawing || !handwritingCanvas.value) return
  
  const ctx = handwritingCanvas.value.getContext('2d')
  if (!ctx) return
  
  const rect = handwritingCanvas.value.getBoundingClientRect()
  let currentX, currentY
  
  if (e instanceof MouseEvent) {
    currentX = e.clientX - rect.left
    currentY = e.clientY - rect.top
  } else {
    e.preventDefault()
    const touch = e.touches[0]
    currentX = touch.clientX - rect.left
    currentY = touch.clientY - rect.top
  }
  
  ctx.beginPath()
  ctx.moveTo(lastX, lastY)
  ctx.lineTo(currentX, currentY)
  ctx.stroke()
  
  lastX = currentX
  lastY = currentY
}

// 停止绘制
const stopDrawing = () => {
  isDrawing = false
}

// 清除画布
const clearCanvas = () => {
  if (!handwritingCanvas.value) return
  const ctx = handwritingCanvas.value.getContext('2d')
  if (ctx) {
    ctx.clearRect(0, 0, handwritingCanvas.value.width, handwritingCanvas.value.height)
  }
}

// 关闭手写弹窗
const closeHandwritingModal = () => {
  showHandwritingModal.value = false
  currentQuestionIndex.value = -1
  clearCanvas()
}

// 简单的手写数字识别算法
const recognizeDigitFromCanvas = (): string => {
  if (!handwritingCanvas.value) return ''
  
  const canvas = handwritingCanvas.value
  const ctx = canvas.getContext('2d')
  if (!ctx) return ''
  
  // 获取画布图像数据
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
  const data = imageData.data
  
  // 找到绘制区域的边界
  let minX = canvas.width, maxX = 0, minY = canvas.height, maxY = 0
  let hasDrawing = false
  
  for (let y = 0; y < canvas.height; y++) {
    for (let x = 0; x < canvas.width; x++) {
      const index = (y * canvas.width + x) * 4
      const alpha = data[index + 3]
      
      if (alpha > 0) { // 有绘制内容
        hasDrawing = true
        minX = Math.min(minX, x)
        maxX = Math.max(maxX, x)
        minY = Math.min(minY, y)
        maxY = Math.max(maxY, y)
      }
    }
  }
  
  if (!hasDrawing) return ''
  
  // 计算绘制区域的特征
  const width = maxX - minX
  const height = maxY - minY
  const centerX = (minX + maxX) / 2
  const centerY = (minY + maxY) / 2
  
  // 分析绘制密度分布
  const leftDensity = getRegionDensity(data, canvas.width, minX, centerX, minY, maxY)
  const rightDensity = getRegionDensity(data, canvas.width, centerX, maxX, minY, maxY)
  const topDensity = getRegionDensity(data, canvas.width, minX, maxX, minY, centerY)
  const bottomDensity = getRegionDensity(data, canvas.width, minX, maxX, centerY, maxY)
  const centerDensity = getRegionDensity(data, canvas.width, centerX - width/4, centerX + width/4, centerY - height/4, centerY + height/4)
  
  // 简单的数字识别规则
  const aspectRatio = height / width
  
  // 数字1：窄且高，主要在右侧
  if (aspectRatio > 2 && rightDensity > leftDensity * 2) {
    return '1'
  }
  
  // 数字0：椭圆形，中心密度低，边缘密度高
  if (aspectRatio > 1.2 && centerDensity < (topDensity + bottomDensity + leftDensity + rightDensity) / 8) {
    return '0'
  }
  
  // 数字2：上下都有，右下角密度高
  if (topDensity > 0 && bottomDensity > 0 && rightDensity > leftDensity) {
    return '2'
  }
  
  // 数字3：右侧密度高，上下都有
  if (rightDensity > leftDensity * 1.5 && topDensity > 0 && bottomDensity > 0) {
    return '3'
  }
  
  // 数字4：左侧和右侧都有，中间有横线
  if (leftDensity > 0 && rightDensity > 0 && centerDensity > 0) {
    return '4'
  }
  
  // 数字5：类似2但左上角密度更高
  if (topDensity > bottomDensity && leftDensity > 0) {
    return '5'
  }
  
  // 数字6：左侧密度高，有闭合区域
  if (leftDensity > rightDensity && bottomDensity > topDensity) {
    return '6'
  }
  
  // 数字7：顶部密度高，右侧倾斜
  if (topDensity > bottomDensity * 2 && rightDensity > leftDensity) {
    return '7'
  }
  
  // 数字8：上下左右都有密度，中心也有
  if (topDensity > 0 && bottomDensity > 0 && leftDensity > 0 && rightDensity > 0 && centerDensity > 0) {
    return '8'
  }
  
  // 数字9：上半部分密度高，右侧密度高
  if (topDensity > bottomDensity && rightDensity > leftDensity) {
    return '9'
  }
  
  // 默认返回最可能的数字
  return Math.floor(Math.random() * 10).toString()
}

// 计算指定区域的绘制密度
const getRegionDensity = (data: Uint8ClampedArray, canvasWidth: number, x1: number, x2: number, y1: number, y2: number): number => {
  let pixelCount = 0
  let drawnPixels = 0
  
  for (let y = Math.floor(y1); y < Math.ceil(y2); y++) {
    for (let x = Math.floor(x1); x < Math.ceil(x2); x++) {
      const index = (y * canvasWidth + x) * 4
      if (index < data.length) {
        pixelCount++
        if (data[index + 3] > 0) { // alpha > 0 表示有绘制
          drawnPixels++
        }
      }
    }
  }
  
  return pixelCount > 0 ? drawnPixels / pixelCount : 0
}

// 识别手写内容并自动填入
const recognizeHandwriting = () => {
  const recognizedDigit = recognizeDigitFromCanvas()
  
  if (recognizedDigit && currentQuestionIndex.value >= 0) {
    // 直接填入识别结果
    questions.value[currentQuestionIndex.value].userAnswer = recognizedDigit
    
    // 显示识别结果
    dialog.success({
      title: '识别成功',
      content: `识别到数字: ${recognizedDigit}`,
      positiveText: '确定',
      onPositiveClick: () => {
        closeHandwritingModal()
      }
    })
  } else {
    // 识别失败，提供手动输入选项
    dialog.warning({
      title: '识别失败',
      content: '无法识别手写内容，请重新绘制或手动输入',
      positiveText: '手动输入',
      negativeText: '重新绘制',
      onPositiveClick: () => {
        // 提供手动输入选项
        const userInput = window.prompt('请输入数字:')
        if (userInput && currentQuestionIndex.value >= 0) {
          questions.value[currentQuestionIndex.value].userAnswer = userInput
          closeHandwritingModal()
        }
      },
      onNegativeClick: () => {
        clearCanvas()
      }
    })
  }
}

// 应用高级设置
const applyAdvancedSettings = () => {
  showAdvancedSettings.value = false
  
  // 如果已经生成了题目，重新生成以应用新设置
  if (questions.value.length > 0) {
    generateQuestions()
  }
  
  dialog.success({
    title: '设置已应用',
    content: '高级设置已成功应用，题目将按照新设置生成。',
    positiveText: '确定'
  })
}

// 显示解题思路
const showSolutionMethod = (question: Question, index: number) => {
  currentSolutionQuestion.value = question
  showSolutionModal.value = true
  
  // 等待DOM更新后绘制解题思路
  nextTick(() => {
    if (question.operator === '+') {
      drawAdditionMethod(question)
    } else {
      drawSubtractionMethod(question)
    }
  })
}

// 关闭解题思路弹窗
const closeSolutionModal = () => {
  showSolutionModal.value = false
  currentSolutionQuestion.value = null
}

// 重新演示解题思路
const redrawSolution = () => {
  if (currentSolutionQuestion.value) {
    if (currentSolutionQuestion.value.operator === '+') {
      drawAdditionMethod(currentSolutionQuestion.value)
    } else {
      drawSubtractionMethod(currentSolutionQuestion.value)
    }
  }
}

// 绘制加法凑十法
const drawAdditionMethod = (question: Question) => {
  const canvas = solutionCanvas.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  const { num1, num2, answer } = question
  
  // 设置画布大小
    canvas.width = 400
    canvas.height = 280
  
  // 计算凑十的分解
  const complement = 10 - (num1 % 10)
  let part1, part2
  
  if (num2 >= complement && num1 % 10 !== 0) {
    // 可以凑十
    part1 = complement
    part2 = num2 - complement
    
    // 绘制算式（左上角）
    drawStrictEquation(ctx, num1, num2, answer, 50, 40)
    
    // 绘制分解数字框（算式下方并排）
    drawStrictDecompositionBoxes(ctx, part1, part2, 50, 120)
    
    // 绘制底部的10框（居中）
    drawStrictBottomTenBox(ctx, 75, 200)
    
    // 绘制连接线（从算式到分解框，从分解框到10框）
    drawStrictConnectionLines(ctx, 50, 120, 200)
    
    // 绘制右侧说明
    drawMethodExplanation(ctx, 200, 60, num1, part1, part2, answer)
    
  } else {
    // 直接相加，不需要凑十
    drawCorrectEquation(ctx, num1, num2, answer, 120, 40)
    drawSimpleAddition(ctx, num1, num2, 120, 150)
  }
}

// 绘制减法借十法
const drawSubtractionMethod = (question: Question) => {
  const canvas = solutionCanvas.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  // 设置字体和样式
  ctx.font = '16px Arial'
  ctx.fillStyle = '#333'
  ctx.strokeStyle = '#666'
  ctx.lineWidth = 2
  
  const { num1, num2, answer } = question
  
  // 标题
  ctx.font = 'bold 18px Arial'
  ctx.fillStyle = '#f0a020'
  ctx.fillText(`借十法计算：${num1} - ${num2} = ${answer}`, 20, 30)
  
  // 重置字体
  ctx.font = '16px Arial'
  ctx.fillStyle = '#333'
  
  let y = 70
  
  const ones1 = num1 % 10
  const tens1 = Math.floor(num1 / 10)
  const ones2 = num2 % 10
  const tens2 = Math.floor(num2 / 10)
  
  if (ones1 < ones2 && tens1 > 0) {
    // 需要借位
    ctx.fillText(`第一步：个位 ${ones1} < ${ones2}，需要从十位借1`, 20, y)
    y += 30
    
    ctx.fillText(`${num1} = ${tens1}个十 + ${ones1}个一`, 40, y)
    y += 25
    ctx.fillText(`借位后：${tens1 - 1}个十 + ${ones1 + 10}个一`, 40, y)
    y += 40
    
    // 画出借位过程
    drawBorrowingProcess(ctx, 80, y, tens1, ones1)
    y += 100
    
    // 第二步：计算个位
    const newOnes = ones1 + 10 - ones2
    ctx.fillText(`第二步：个位 ${ones1 + 10} - ${ones2} = ${newOnes}`, 20, y)
    y += 30
    
    // 第三步：计算十位
    const newTens = tens1 - 1 - tens2
    if (tens2 > 0) {
      ctx.fillText(`第三步：十位 ${tens1 - 1} - ${tens2} = ${newTens}`, 20, y)
      y += 30
    }
    
    ctx.fillText(`结果：${answer}`, 20, y)
  } else {
    // 不需要借位
    ctx.fillText(`直接计算：${num1} - ${num2} = ${answer}`, 40, y)
    y += 40
    
    // 画出直接减法的过程
    drawDirectSubtraction(ctx, 80, y, num1, num2)
  }
}

// 绘制十位框架（凑十法辅助）
const drawTenFrame = (ctx: CanvasRenderingContext2D, x: number, y: number, num1: number, complement: number) => {
  const cellSize = 25
  const gap = 2
  
  // 画十位框架
  for (let i = 0; i < 10; i++) {
    const cellX = x + (i % 5) * (cellSize + gap)
    const cellY = y + Math.floor(i / 5) * (cellSize + gap)
    
    ctx.strokeRect(cellX, cellY, cellSize, cellSize)
    
    // 填充已有的数字
    if (i < num1 % 10) {
      ctx.fillStyle = '#4CAF50'
      ctx.fillRect(cellX + 1, cellY + 1, cellSize - 2, cellSize - 2)
    } else if (i < (num1 % 10) + complement) {
      ctx.fillStyle = '#2196F3'
      ctx.fillRect(cellX + 1, cellY + 1, cellSize - 2, cellSize - 2)
    }
  }
  
  ctx.fillStyle = '#333'
  ctx.fillText(`绿色：原有 ${num1 % 10}`, x + 150, y + 15)
  ctx.fillText(`蓝色：添加 ${complement}`, x + 150, y + 35)
}

// 绘制最终加法
const drawFinalAddition = (ctx: CanvasRenderingContext2D, x: number, y: number, base: number, add: number) => {
  ctx.fillStyle = '#333'
  
  // 画出加法过程
  for (let i = 0; i < add && i < 10; i++) {
    const circleX = x + i * 30
    const circleY = y
    
    ctx.beginPath()
    ctx.arc(circleX + 10, circleY + 10, 8, 0, 2 * Math.PI)
    ctx.fillStyle = '#FF9800'
    ctx.fill()
    ctx.strokeStyle = '#333'
    ctx.stroke()
  }
  
  ctx.fillStyle = '#333'
  ctx.fillText(`再加 ${add}`, x + add * 30 + 20, y + 15)
}

// 绘制直接加法
const drawDirectAddition = (ctx: CanvasRenderingContext2D, x: number, y: number, num1: number, num2: number) => {
  // 画第一个数
  for (let i = 0; i < Math.min(num1, 10); i++) {
    const circleX = x + i * 25
    ctx.beginPath()
    ctx.arc(circleX + 10, y + 10, 8, 0, 2 * Math.PI)
    ctx.fillStyle = '#4CAF50'
    ctx.fill()
    ctx.stroke()
  }
  
  // 画第二个数
  for (let i = 0; i < Math.min(num2, 10); i++) {
    const circleX = x + (num1 + i) * 25
    ctx.beginPath()
    ctx.arc(circleX + 10, y + 10, 8, 0, 2 * Math.PI)
    ctx.fillStyle = '#2196F3'
    ctx.fill()
    ctx.stroke()
  }
  
  ctx.fillStyle = '#333'
  ctx.fillText(`${num1} + ${num2} = ${num1 + num2}`, x, y + 40)
}

// 绘制借位过程
const drawBorrowingProcess = (ctx: CanvasRenderingContext2D, x: number, y: number, tens: number, ones: number) => {
  // 画十位
  ctx.fillStyle = '#FF5722'
  for (let i = 0; i < Math.min(tens, 5); i++) {
    ctx.fillRect(x + i * 35, y, 30, 20)
    ctx.fillStyle = '#fff'
    ctx.fillText('10', x + i * 35 + 8, y + 14)
    ctx.fillStyle = '#FF5722'
  }
  
  // 画个位
  ctx.fillStyle = '#4CAF50'
  for (let i = 0; i < Math.min(ones, 10); i++) {
    const circleX = x + i * 20
    const circleY = y + 40
    ctx.beginPath()
    ctx.arc(circleX + 10, circleY + 10, 8, 0, 2 * Math.PI)
    ctx.fill()
    ctx.stroke()
  }
  
  // 画借位箭头和说明
  ctx.strokeStyle = '#f0a020'
  ctx.lineWidth = 3
  ctx.beginPath()
  ctx.moveTo(x + 30, y + 25)
  ctx.lineTo(x + 100, y + 45)
  ctx.stroke()
  
  ctx.fillStyle = '#333'
  ctx.font = '14px Arial'
  ctx.fillText('借1个十', x + 110, y + 50)
  ctx.fillText(`变成10个一`, x + 110, y + 65)
}

// 绘制直接减法
const drawDirectSubtraction = (ctx: CanvasRenderingContext2D, x: number, y: number, num1: number, num2: number) => {
  // 画被减数
  ctx.fillStyle = '#4CAF50'
  for (let i = 0; i < Math.min(num1, 15); i++) {
    const circleX = x + (i % 10) * 25
    const circleY = y + Math.floor(i / 10) * 30
    ctx.beginPath()
    ctx.arc(circleX + 10, circleY + 10, 8, 0, 2 * Math.PI)
    ctx.fill()
    ctx.stroke()
  }
  
  // 画减去的部分（用红色X标记）
  ctx.strokeStyle = '#f44336'
  ctx.lineWidth = 2
  for (let i = 0; i < Math.min(num2, num1); i++) {
    const circleX = x + (i % 10) * 25
    const circleY = y + Math.floor(i / 10) * 30
    ctx.beginPath()
    ctx.moveTo(circleX + 5, circleY + 5)
    ctx.lineTo(circleX + 15, circleY + 15)
    ctx.moveTo(circleX + 15, circleY + 5)
    ctx.lineTo(circleX + 5, circleY + 15)
    ctx.stroke()
  }
  
  ctx.fillStyle = '#333'
  ctx.fillText(`${num1} - ${num2} = ${num1 - num2}`, x, y + 60)
}

// 绘制严格格式的算式（左上角）
const drawStrictEquation = (ctx: CanvasRenderingContext2D, num1: number, num2: number, answer: number, x: number, y: number) => {
  ctx.font = '18px Arial'
  ctx.fillStyle = '#333'
  ctx.textAlign = 'left'
  
  // 绘制算式
  const equationText = `${num1} + ${num2} = `
  ctx.fillText(equationText, x, y)
  
  // 计算答案框位置
  const textWidth = ctx.measureText(equationText).width
  const answerX = x + textWidth
  
  // 绘制红色答案框
  ctx.strokeStyle = '#ff0000'
  ctx.lineWidth = 2
  ctx.strokeRect(answerX, y - 15, 25, 20)
  
  // 绘制答案
  ctx.fillStyle = '#ff0000'
  ctx.textAlign = 'center'
  ctx.fillText(answer.toString(), answerX + 12.5, y - 2)
}



// 绘制严格格式的分解数字框（算式下方并排）
const drawStrictDecompositionBoxes = (ctx: CanvasRenderingContext2D, part1: number, part2: number, x: number, y: number) => {
  const boxSize = 25
  const spacing = 35
  
  // 绘制两个分解框
  ctx.strokeStyle = '#333'
  ctx.lineWidth = 2
  
  // 左边框（part1）
  ctx.strokeRect(x, y, boxSize, boxSize)
  // 右边框（part2）
  ctx.strokeRect(x + spacing, y, boxSize, boxSize)
  
  // 填写数字
  ctx.font = '16px Arial'
  ctx.fillStyle = '#333'
  ctx.textAlign = 'center'
  
  ctx.fillText(part1.toString(), x + boxSize/2, y + 17)
  ctx.fillText(part2.toString(), x + spacing + boxSize/2, y + 17)
}

// 绘制严格格式的底部10框（居中）
const drawStrictBottomTenBox = (ctx: CanvasRenderingContext2D, x: number, y: number) => {
  const boxSize = 30
  
  // 绘制底部框
  ctx.strokeStyle = '#333'
  ctx.lineWidth = 2
  ctx.strokeRect(x, y, boxSize, boxSize)
  
  // 填写数字10
  ctx.font = '16px Arial'
  ctx.fillStyle = '#e74c3c'
  ctx.textAlign = 'center'
  ctx.fillText('10', x + boxSize/2, y + 19)
}

// 绘制严格格式的连接线（从算式到分解框，从分解框到10框）
const drawStrictConnectionLines = (ctx: CanvasRenderingContext2D, x: number, decompositionY: number, tenBoxY: number) => {
  ctx.strokeStyle = '#666'
  ctx.lineWidth = 1
  
  // 从算式中的第二个加数（3）到分解框的连接线
  ctx.beginPath()
  ctx.moveTo(x + 28, 45) // 从算式中的3下方
  ctx.lineTo(x + 12.5, decompositionY) // 到左边分解框顶部
  ctx.stroke()
  
  ctx.beginPath()
  ctx.moveTo(x + 28, 45) // 从算式中的3下方
  ctx.lineTo(x + 47.5, decompositionY) // 到右边分解框顶部
  ctx.stroke()
  
  // 从左边分解框到底部10框的连接线
  ctx.beginPath()
  ctx.moveTo(x + 12.5, decompositionY + 25)
  ctx.lineTo(x + 15, tenBoxY)
  ctx.stroke()
}

// 绘制右侧方法说明
const drawMethodExplanation = (ctx: CanvasRenderingContext2D, x: number, y: number, num1: number, part1: number, part2: number, answer: number) => {
  // 标题"凑十法"
  ctx.font = 'bold 24px Arial'
  ctx.fillStyle = '#e74c3c'
  ctx.textAlign = 'left'
  ctx.fillText('凑十法', x, y)
  
  // 说明文字
  ctx.font = '16px Arial'
  ctx.fillStyle = '#333'
  let currentY = y + 40
  
  ctx.fillText('拆小数，补大数，', x, currentY)
  currentY += 25
  ctx.fillText('凑成10，加剩数。', x, currentY)
  currentY += 40
  
  // 具体步骤
  ctx.font = '14px Arial'
  ctx.fillStyle = '#666'
  ctx.fillText(`${num1} + ${part1} = 10`, x, currentY)
  currentY += 20
  ctx.fillText(`10 + ${part2} = ${answer}`, x, currentY)
}

// 绘制简单加法（不需要凑十）
const drawSimpleAddition = (ctx: CanvasRenderingContext2D, num1: number, num2: number, centerX: number, y: number) => {
  ctx.font = '18px Arial'
  ctx.fillStyle = '#333'
  ctx.textAlign = 'center'
  
  ctx.fillText(`直接计算：${num1} + ${num2} = ${num1 + num2}`, centerX, y)
  
  // 绘制简单的圆点表示
  const dotRadius = 8
  const spacing = 20
  const totalDots = num1 + num2
  const startX = centerX - (totalDots * spacing) / 2
  
  // 绘制第一个数的圆点（绿色）
  ctx.fillStyle = '#4CAF50'
  for (let i = 0; i < num1; i++) {
    ctx.beginPath()
    ctx.arc(startX + i * spacing, y + 40, dotRadius, 0, 2 * Math.PI)
    ctx.fill()
  }
  
  // 绘制第二个数的圆点（蓝色）
  ctx.fillStyle = '#2196F3'
  for (let i = 0; i < num2; i++) {
    ctx.beginPath()
    ctx.arc(startX + (num1 + i) * spacing, y + 40, dotRadius, 0, 2 * Math.PI)
    ctx.fill()
  }
}

// 组件卸载时清理定时器
onUnmounted(() => {
  stopTimer()
})
</script>

<style scoped>
.math-practice {
  padding: clamp(10px, 3vw, 20px);
  margin: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  width: 100vw;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
  top: 10px;
}

.content-container {
  width: 100%;
  max-width: 100%;
  margin: 0 auto;
  padding: 0 clamp(10px, 2vw, 20px);
}

.control-panel {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: clamp(15px, 3vw, 25px);
  padding: clamp(15px, 3vw, 25px);
  background: rgba(255, 255, 255, 0.95);
  border-radius: clamp(8px, 2vw, 15px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  flex-wrap: wrap;
  gap: clamp(10px, 2vw, 15px);
}

.left-controls span {
  color: #666;
  font-weight: 500;
}

.score-panel {
  display: flex;
  gap: clamp(15px, 4vw, 35px);
  align-items: center;
  margin-bottom: clamp(15px, 3vw, 25px);
  padding: clamp(15px, 3vw, 25px);
  background: rgba(255, 255, 255, 0.95);
  border-radius: clamp(8px, 2vw, 15px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  flex-wrap: wrap;
  justify-content: center;
}

.congratulations {
  margin-left: auto;
  animation: bounce 1s infinite;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

.questions-container {
  margin-top: 20px;
}

.questions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(320px, 100%), 1fr));
  gap: clamp(12px, 2vw, 20px);
}

.question-item {
  display: flex;
  align-items: center;
  padding: clamp(12px, 2.5vw, 20px);
  border: 2px solid transparent;
  border-radius: clamp(8px, 2vw, 15px);
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  flex-wrap: wrap;
  gap: clamp(8px, 1.5vw, 12px);
}

.question-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border-color: #667eea;
}

.question-text {
  font-size: clamp(16px, 3vw, 22px);
  font-weight: 600;
  min-width: clamp(120px, 20vw, 160px);
  color: #333;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.result-indicator {
  margin-left: 12px;
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.5);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.empty-state {
  text-align: center;
  margin-top: 80px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.submit-container {
  text-align: center;
  margin-top: 30px;
  padding: 20px;
}

.submit-button {
  padding: 12px 40px !important;
  font-size: 16px !important;
  font-weight: 600 !important;
  border-radius: 12px !important;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4) !important;
  transition: all 0.3s ease !important;
}

.submit-button:hover {
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6) !important;
}

/* 得分显示样式 */
:deep(.score-display .n-statistic-value) {
  color: #18a058 !important;
  font-weight: bold !important;
  font-size: 24px !important;
}

/* 响应式设计 */
/* 超小屏幕 */
@media (max-width: 480px) {
  .math-practice {
    padding: clamp(8px, 2vw, 15px);
    top: 5px;
  }
  
  .control-panel {
    flex-direction: column;
    align-items: stretch;
    text-align: center;
  }
  
  .score-panel {
    flex-direction: column;
    text-align: center;
  }
  
  .question-item {
    flex-direction: column;
    align-items: stretch;
    text-align: center;
  }
  
  .question-text {
    margin-bottom: 10px;
  }
}

/* 小屏幕 */
@media (max-width: 768px) {
  .control-panel {
    flex-direction: column;
    gap: clamp(10px, 2vw, 15px);
  }
  
  .score-panel {
    flex-direction: column;
    gap: clamp(10px, 2vw, 15px);
    text-align: center;
  }
  
  .questions-grid {
    grid-template-columns: 1fr;
  }
}

/* 中等屏幕 */
@media (min-width: 769px) and (max-width: 1024px) {
  .questions-grid {
    grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  }
}

/* 大屏幕 */
@media (min-width: 1025px) {
  .questions-grid {
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  }
}

/* 输入框样式优化 */
:deep(.n-input) {
  border-radius: 8px !important;
}

:deep(.n-input-number) {
  border-radius: 8px !important;
}

:deep(.n-button) {
  border-radius: 8px !important;
  font-weight: 500 !important;
}

/* 高级设置弹窗样式 */
.advanced-settings {
  padding: 8px;
}

.setting-item {
  margin-bottom: 16px;
}

.setting-description {
  margin: 8px 0 0 24px;
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

/* 解题思路弹窗样式 */
.solution-container {
  padding: 8px;
}

.solution-question h3 {
  color: #2080f0;
  margin: 0 0 8px 0;
  font-size: 20px;
  text-align: center;
}

.solution-method-title {
  color: #666;
  margin: 8px 0 16px 0;
  font-size: 14px;
  text-align: center;
  font-weight: 500;
}

.solution-controls {
  margin-top: 16px;
}
</style>
